/**
 * 
 */
package a.thread;

import android.app.IntentService;
import android.content.Context;
import android.content.Intent;
import android.os.PowerManager;

/**
 * 
 * @author tqthe
 *
 */
public abstract class WakefulIntentService extends IntentService {
    private static PowerManager.WakeLock mWakeLock;
    private static final Object LOCK = WakefulIntentService.class;

    public WakefulIntentService(String name) {
        super(name);
    }

    public static void runIntentService(Context context, Intent intent) {
        synchronized (LOCK) {
            if (mWakeLock == null) {
                PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
                mWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "intentservice_wakelock");
            }
        }
        mWakeLock.acquire();

        context.startService(intent);
    }

    @Override
    protected final void onHandleIntent(Intent intent) {
        try {
            doHandleIntent(intent);
        } finally {
            synchronized (LOCK) {
                mWakeLock.release();
            }
        }
    }

    /**
     * 
     * @param intent 
     */
    protected abstract void doHandleIntent(Intent intent);
}
